package com.bizmda.bizsip.app.config;

import cn.hutool.core.io.resource.ClassPathResource;
import com.bizmda.bizsip.app.controlrule.ControlRuleMetricConfig;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizResultEnum;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 史正烨
 */
@Slf4j
@Getter
public class ControlRuleMetricConfigMapping {
    private String configPath;
    private Map<String, ControlRuleMetricConfig> metricMap;

    public ControlRuleMetricConfigMapping(String configPath) throws BizException {
        this.configPath = configPath;
        this.load();
    }

    public void load() throws BizException {
        Yaml yaml = new Yaml();
        Map<String, Object> controlRuleMap = null;
        this.metricMap = new HashMap<>(16);
        try {
            if (this.configPath == null) {
                ClassPathResource resource = new ClassPathResource("/control-rule.yml");
                controlRuleMap = (Map<String, Object>) yaml.load(new FileInputStream(resource.getFile()));
            } else {
                controlRuleMap = (Map<String, Object>) yaml.load(new FileInputStream(new File(this.configPath + "/control-rule.yml")));
            }
        } catch (FileNotFoundException e) {
            log.warn("control-rule.yml文件不存在!");
            return;
        }
        List<Map<String,Object>> metircList = (List<Map<String,Object>>)controlRuleMap.get("metrics");
        ControlRuleMetricConfig metricConfig = null;
        for (Map<String, Object> metricMap : metircList) {
                metricConfig = new ControlRuleMetricConfig(metricMap);
            this.metricMap.put(metricConfig.getName(), metricConfig);
        }
    }

    public ControlRuleMetricConfig getMetric(String name) {
        return this.metricMap.get(name);
    }
}
